<template>
  <Card>
    <div class="searchBox">
      <Form ref="searchForm" :label-width="90" :model="searchForm" class="search-formApply" inline>
        <Form-item label="单号：" prop="number">
          <Input
            v-model="searchForm.number"
            clearable
            placeholder="支持模糊搜索"
            style="width: 200px"
            type="text"
          />
        </Form-item>
        <Form-item label="车牌号：" prop="license_plate_num">
          <Input
            v-model="searchForm.license_plate_num"
            clearable
            placeholder="支持模糊搜索"
            style="width: 200px"
            type="text"
          />
        </Form-item>
        <Form-item label="日期范围：" prop="date">
          <DatePicker
            v-model="searchForm.date"
            placeholder="请选择日期范围"
            placement="bottom-start"
            style="width: 200px"
            type="daterange"
          ></DatePicker>
        </Form-item>
        <Form-item style="margin-left:-90px;">
          <Button icon="md-search" type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
        </Form-item>
      </Form>
    </div>
    <div class="table">
      <Row>
        <Table
          ref="table"
          :columns="columns"
          :data="data"
          :loading="loading"
          border
          size="small"
        >
          <template slot="action" slot-scope="{ row }">
            <Button
              ghost
              style="color:#2d8cf0;font-size: 12px;"
              type="text"
              @click="preview(row)"
            >查看详情
            </Button>
          </template>
        </Table>
      </Row>
      <Row class="page" justify="end" type="flex">
        <Page
          :current="searchForm.pageNumber"
          :page-size="searchForm.pageSize"
          :total="total"
          show-total
          @on-change="changePage"
        />
      </Row>
    </div>
    <Modal
      v-model="modalApplyVisible"
      :mask-closable="false"
      :styles="{top: '20px'}"
      :title="modalApplyTitle"
      :width="900"
    >
      <Tabs value="维修详情">
        <TabPane label="维修详情" name="维修详情">
          <Form
            ref="formApply"
            :label-width="110"
            :model="formApply"
            :rules="formApplyValidate"
            label-position="right"
          >
            <Alert v-if="openErrorAlert" show-icon type="error">
              审核意见
              <span slot="desc">{{ formApply.reason }}</span>
            </Alert>
            <Divider v-if="openErrorAlert"/>
            <Col span="12">
            <FormItem v-if="isShowNumber" label="单号：" prop="number">
              <Input v-model="formApply.number" readonly type="text"/>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="车辆线路：" prop="line">
              <Input v-model="formApply.line" :readonly="isReadonly" type="text"/>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="车牌号：" prop="license_plate_num">
              <Input v-model="formApply.license_plate_num" :readonly="isReadonly" type="text"/>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="日期：" prop="date">
              <DatePicker
                v-model="formApply.date"
                :clearable="false"
                :readonly="isReadonly"
                format="yyyy-MM-dd"
                placeholder="选择时间"
                type="date"
              ></DatePicker>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="驾驶员：" prop="driver">
              <Input v-model="formApply.driver" readonly type="text"/>
            </FormItem>
            </Col>
            <Col span="24">
            <FormItem label="维修情况：" prop="description">
              <Input
                v-model="formApply.description"
                :autosize="{minRows: 4,maxRows: 5}"
                :readonly="isReadonly"
                :rows="4"
                placeholder="请输入..."
                type="textarea"
              ></Input>
            </FormItem>
            </Col>
            <Col span="24">
            <FormItem label="上传照片：" prop="driverUploadFile">
              <upload-pic-thumb-multiple
                ref="driverUploadFile"
                :params="{saveDir: 'mrApply', type: 'pic'}"
                :readonly="isReadonly"
                @on-change="formApply.driverUploadFile=$event"
              ></upload-pic-thumb-multiple>
              <div
                style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
              >1、支持jpg、jpeg、png格式的图片，最大不超过600KB
              </div>
              <div
                style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
              >2、请确保上传完毕之后再提交保存
              </div>
            </FormItem>
            </Col>
            <div v-if="displayHouqinForm">
              <Divider>后勤部</Divider>
              <FormItem label="维修费估值：" prop="appraisal">
                <InputNumber
                  v-model="formApply.appraisal"
                  :max="10000000"
                  :min="0"
                  :readonly="isHouQinReadonly"
                  style="width: 100%"
                ></InputNumber>
              </FormItem>
              <FormItem label="维修厂：" prop="repairer">
                <Input
                  v-model="formApply.repairer"
                  :readonly="isHouQinReadonly"
                  style="width: 100%"
                ></Input>
              </FormItem>
              <FormItem label="上传照片：" prop="houqinUploadFile">
                <upload-pic-thumb-multiple
                  ref="houqinUploadFile"
                  :params="{saveDir: 'mrApply', type: 'pic'}"
                  :readonly="isHouQinReadonly"
                  @on-change="formApply.houqinUploadFile=$event"
                ></upload-pic-thumb-multiple>
                <div
                  style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
                >1、支持jpg、jpeg、png格式的图片，最大不超过600KB
                </div>
                <div
                  style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
                >2、请确保上传完毕之后再提交保存
                </div>
              </FormItem>
            </div>
            <div v-if="displayWeixiuForm">
              <Divider>维修厂</Divider>
              <Row>
                <Col span="12">
                <Form-item label="进厂时间：" prop="enter_at">
                  <DatePicker
                    v-model="formApply.enter_at"
                    :editable="false"
                    placeholder="选择时间"
                    readonly
                    type="datetime"
                  ></DatePicker>
                </Form-item>
                </Col>
                <Col span="12">
                <Form-item label="出厂时间：" prop="out_at">
                  <DatePicker
                    v-model="formApply.out_at"
                    :editable="false"
                    placeholder="选择时间"
                    readonly
                    type="datetime"
                  ></DatePicker>
                </Form-item>
                </Col>
              </Row>
              <Row>
                <Col span="12">
                <Form-item label="维修时长：" prop="working_hours">
                  <Input v-model="working_hours" placeholder="自动计算" readonly/>
                </Form-item>
                </Col>
              </Row>
              <Divider orientation="left">材料单</Divider>
              <div style="margin-bottom:15px">
                <Table
                  ref="selection"
                  :columns="payColumns"
                  :data="payData"
                  :loading="payLoading"
                  border
                  size="small"
                  stripe
                >
                </Table>
              </div>
              <Row>
                <Col span="12">
                <Form-item label="材料费用合计：" prop="material_money">
                  <Input v-model="formApply.material_money" placeholder="" readonly/>
                </Form-item>
                </Col>
              </Row>
              <Divider orientation="left">维修单</Divider>
              <div style="margin-bottom:15px">
                <Table
                  ref="selection"
                  :columns="costColumns"
                  :data="costData"
                  :loading="costLoading"
                  border
                  size="small"
                  stripe
                >
                </Table>
              </div>
              <Row>
                <Col span="12">
                <Form-item label="维修费用合计：" prop="cost_money">
                  <Input v-model="formApply.cost_money" placeholder="自动计算" readonly/>
                </Form-item>
                </Col>
              </Row>
              <Divider/>
              <FormItem label="上传照片：" prop="weixiuUploadFile">
                <upload-pic-thumb-multiple
                  ref="weixiuUploadFile"
                  :params="{saveDir: 'mrApply', type: 'pic'}"
                  :readonly="isHouQinReadonly"
                  @on-change="formApply.weixiuUploadFile=$event"
                ></upload-pic-thumb-multiple>
                <div
                  style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
                >1、支持jpg、jpeg、png格式的图片，最大不超过600KB
                </div>
                <div
                  style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
                >2、请确保上传完毕之后再提交保存
                </div>
              </FormItem>
              <Row>
                <Col span="12">
                <Form-item label="费用总合计：" prop="total_money">
                  <Input v-model="formApply.total_money" placeholder="自动计算" readonly/>
                </Form-item>
                </Col>
              </Row>
            </div>
          </Form>
        </TabPane>
        <TabPane v-if="isShowAuditRecord" label="审核记录" name="审核记录">
          <div id="auditRecord">
            <div v-for="item of auditRecord" :key="item.id" class="stepCard">
              <div>
                <p>
                  <Icon size="30" type="md-contact"/>
                  {{ item.nodeName }}
                </p>
                <span>时间：{{ item.created_at }}&nbsp;&nbsp;&nbsp;&nbsp;操作：{{ item.resultName }}</span>
                <span v-if="item.reason !== null && item.reason !== ''">退回理由：{{ item.reason }}</span>
              </div>
              <div>
                <p>单据编号：{{ item.number }}</p>
                <div v-if="item.signature !== null"><p>签名：</p><img :src="item.signature" alt=""></div>
              </div>
              <div></div>
            </div>
          </div>
        </TabPane>
      </Tabs>
      <div slot="footer">
      </div>
    </Modal>
  </Card>
</template>
<script>
import moment from 'moment'
import UploadPicThumbMultiple from '../my-components/upload-pic-thumb-multiple'
import {applyDoneList, auditApply, editAppply, storeApply, storeWeixiu, updateApply} from '../../api/mrDone'

export default {
  components: {
    UploadPicThumbMultiple
  },
  data() {
    return {
      displayHouqinForm: false,
      displayWeixiuForm: false,
      isShowAuditRecord: false,
      nodeKey: '',
      reasonAuditLoading: false,
      reasonModal: false,
      openErrorAlert: false,
      reason: '',
      isShowCancelBtn: true,
      isShowSaveBtn: true,
      isShowSaveSubmitBtn: true,
      isShowWeixiuSubmitBtn: false,
      isDisabled: false,
      isReadonly: false,
      isHouQinReadonly: false,
      isShowNumber: false,
      isShowAuditBtn: false,
      total: 0,
      searchForm: {
        number: '',
        date: [null, null],
        license_plate_num: '',
        pageNumber: 1,
        pageSize: 10
      },
      reasonForm: {
        reason: ''
      },
      formApply: {
        nodeType: '',
        nodeKey: '',
        number: '',
        line: '',
        appraisal: 0,
        license_plate_num: '',
        driver: this.$store.getters.user.name, // 默认当前用户
        user_id: this.$store.getters.user.id, // 默认当前用户ID
        date: moment().format('YYYY-MM-DD'), //默认今天
        description: '',
        driverUploadFile: [],
        houqinUploadFile: [],
        weixiuUploadFile: [],
        total_money: 0,
        material_money: 0,
        cost_money: 0,
        enter_at: '',
        out_at: '',
      },
      working_hours: 0,
      formCost: {
        line: '',
        license_plate_num: '',
        driver: this.$store.getters.user.name, // 默认当前用户
        date: moment().format('YYYY-MM-DD'), //默认今天
        description: ''
      },
      loading: true,
      columns: [
        {
          type: 'index',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '单号',
          key: 'number',
          width: 150,
          align: 'left',
          fixed: 'left'
        },
        {
          title: '单据日期',
          key: 'date',
          width: 150,
          align: 'center'
        },
        {
          title: '车牌号',
          key: 'license_plate_num',
          width: 120,
          align: 'center'
        },
        {
          title: '线路',
          key: 'line',
          width: 120,
          align: 'center'
        },
        {
          title: '驾驶员',
          key: 'driver',
          width: 120,
          align: 'left'
        },
        {
          title: '发起人',
          key: 'user_name',
          width: 120,
          align: 'left'
        },
        {
          title: '审批操作',
          key: 'result_name',
          width: 150,
          render: (h, params) => {
            const logs = params.row.logs
            const lastLog = logs[logs.length - 1]
            const color = lastLog.result_name === '审核' ? 'success' : lastLog.result_name === '退回' ? 'error' : '#808695'
            const text = lastLog.result_name === '审核' ? '通过' : lastLog.result_name

            return h('Tag', {
              props: {
                type: 'dot',
                color: color
              }
            }, text)
          }
        },
        {
          title: '维修情况',
          key: 'description',
          width: 200,
          align: 'left'
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 170,
          align: 'right'
        },
        {
          title: '操作',
          slot: 'action',
          width: 140,
          fixed: 'right',
          align: 'center'
        }
      ],
      data: [],
      submitApplyLoading: false,
      submitWeixiuLoading: false,
      saveApplyLoading: false,
      submitCostLoading: false,
      modalApplyType: 0,
      modalCostType: 0,
      modalApplyVisible: false,
      modalCostVisible: false,
      formApplyValidate: {
        line: [
          {
            required: true,
            message: '车辆线路不能为空',
            trigger: 'change',
            type: 'number'
          }
        ],
        license_plate_num: [
          {
            required: true,
            message: '车牌号不能为空',
            trigger: 'change',
            type: 'string'
          }
        ],
        // date: [{required: true, message: "时间不能为空", trigger: "blur", type: 'date'}],
        // appraisal: [{ required: true, message: '金额不能为空', trigger: 'blur', type: 'number' }],
      },
      formCostValidate: {
        license_plate_num: [
          {required: true, message: '车牌号不能为空', trigger: 'blur'}
        ]
      },
      modalApplyTitle: '',
      modalCostTitle: '',
      licensePlateNumList: [],
      lines: [],
      disableNodeId: true,
      auditRecord: [],
      addPayForm: {
        title: '',
        unit: '',
        price: '',
        count: '',
        amount: null
      },
      addCostForm: {
        title: '',
        price: '',
      },
      payColumns: [
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '材料名称',
          key: 'title',
          align: 'center'
        },
        {
          title: '单位',
          key: 'unit',
          align: 'center'
        },
        {
          title: '单价',
          key: 'price',
          align: 'center'
        },
        {
          title: '数量',
          key: 'count',
          align: 'center'
        },
        {
          title: '金额',
          key: 'amount',
          align: 'center'
        },
      ],
      costColumns: [
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '维修内容',
          key: 'title',
          align: 'center'
        },
        {
          title: '维修金额',
          key: 'price',
          align: 'center'
        },
      ],
      editPayForm: {},
      editCostForm: {},
      modal: false,
      costModal: false,
      editModal: false,
      editCostModal: false,
      signModal: false,
      payData: [],
      costData: [],
      payLoading: false,
      costLoading: false,
      addPayFormValidate: {},
      editPayFormValidate: {},
    }
  },
  mounted() {
  },
  created() {
    this.getWorkflow()
    this.getLinesArray()
  },
  methods: {
    async getLinesArray() {
      this.lines = await this.getLines()
    },
    getWorkflow() {
      this.init()
      const roleName = this.$store.getters.user.roleName
      if (roleName.indexOf('维修-司机') !== -1) {
        this.nodeKey = 'wr_apply_driver'
      } else if (roleName.indexOf('维修-车队长') !== -1) {
        this.nodeKey = 'wr_apply_driver_leader'
      } else if (roleName.indexOf('维修-后勤部部长') !== -1) {
        this.nodeKey = 'wr_apply_logistics_leader'
      } else if (roleName.indexOf('维修-分管领导') !== -1) {
        this.nodeKey = 'wr_apply_leader'
      } else if (roleName.indexOf('维修-维修厂') !== -1) {
        this.nodeKey = 'wr_apply_repairer'
      } else if (roleName.indexOf('维修-后勤部') !== -1) {
        this.nodeKey = 'wr_apply_logistics'
      } else if (roleName.indexOf('维修-财务部') !== -1) {
        this.nodeKey = 'wr_cost_finance'
      } else {
        this.nodeKey = 'admin'
      }
    },
    changePage(v) {
      this.searchForm.pageNumber = v
      this.getMrApplyList()
    },
    getMrApplyList() {
      this.loading = true
      applyDoneList(this.searchForm).then(res => {
        this.loading = false
        if (res.data) {
          this.data = res.data.mrApplyRecord
          this.total = res.data.count
        }
      })
    },
    handleApplyCancel() {
      this.modalApplyVisible = false
      this.$refs.formApply.resetFields()
    },
    handleApplySubmit(e) {
      this.$refs.formApply.validate(valid => {
        if (valid) {
          this.submitApplyLoading = e === 'submit'
          this.saveApplyLoading = e === 'save'
          this.formApply.nodeType = e
          this.formApply.nodeKey = this.nodeKey
          if (
            this.nodeKey === 'wr_apply_driver' ||
            this.nodeKey === 'wr_apply_driver_leader'
          ) {
            this.formApply.appraisal = 0
            this.formApply.houqinUploadFile = []
          }
          if (this.nodeKey === 'wr_apply_repairer') {
            this.formApply.weixiu = this.payData
          } else {
            this.formApply.weixiuUploadFile = []
          }
          if (this.modalApplyType === 0) {
            delete this.formApply.id
            storeApply(this.formApply).then(res => {
              this.submitApplyLoading = this.saveApplyLoading = false
              if (res.data) {
                this.$Message.success(res.message)
                this.getMrApplyList()
                this.modalApplyVisible = false
              } else {
                this.$Message.error(res.message)
              }
            })
          } else if (this.modalApplyType === 1) {
            updateApply(this.formApply, this.formApply.id).then(res => {
              this.submitApplyLoading = this.saveApplyLoading = false
              if (res.data) {
                this.$Message.success('更新成功')
                this.getMrApplyList()
                this.modalApplyVisible = false
              } else {
                this.$Message.error(res.message)
              }
            })
          } else {
          }
        }
      })
    },
    handleWeixiuSubmit() {
      this.$refs.formApply.validate(valid => {
        if (valid) {
          this.submitWeixiuLoading = true
          const params = {
            detail: this.payData,
            weixiuUploadFile: this.formApply.weixiuUploadFile,
            nodeKey: this.nodeKey,
            nodeType: 'submit'
          }
          storeWeixiu(params, this.formApply.id).then(res => {
            this.submitWeixiuLoading = false
            if (res.data) {
              this.$Message.success('修改成功')
              this.getMrApplyList()
              this.modalApplyVisible = false
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getMrApplyList()
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getMrApplyList()
    },
    init() {
      this.isShowAuditBtn = true
      if (this.nodeKey === 'wr_apply_repairer') {
        this.searchForm.status = 1
      }
      this.getMrApplyList()
    },
    preview(row) {
      this.displayHouqinForm =
        this.nodeKey !== 'wr_apply_driver' &&
        this.nodeKey !== 'wr_apply_driver_leader' &&
        this.nodeKey !== 'wr_apply_repairer'
      this.displayWeixiuForm =
        this.nodeKey === 'wr_apply_repairer' ||
        this.nodeKey === 'wr_apply_logistics' ||
        this.nodeKey === 'wr_cost_finance'
      this.isShowAuditRecord = this.nodeKey !== 'wr_apply_repairer'
      this.isShowWeixiuSubmitBtn = this.nodeKey === 'wr_apply_repairer'
      this.isShowCancelBtn = false
      this.isShowSaveBtn = false
      this.isShowSaveSubmitBtn = false
      this.isShowAuditBtn =
        row.status === 2 && this.nodeKey === row.process.node.node_key && row.process.node.node_key !== 'wr_apply_repairer'
      this.modalApplyType = this.nodeKey === 'wr_apply_repairer' ? 0 : 2
      this.modalApplyTitle = '查看'
      editAppply(row.id).then(res => {
        this.isShowNumber = true
        this.formApply = res.data
        this.payData = res.data.material
        this.costData = res.data.detail
        if (this.formApply.repairer) {
          this.displayReadonlyWeixiuForm = true
        }
        this.working_hours = res.data.working_hours
        this.formApply.cost_money = res.data.cost_money
        this.formApply.material_money = res.data.material_money
        this.formApply.total_money = this.formApply.cost_money + this.formApply.material_money
        this.formApply.driver = res.data.user_name
        this.formApply.appraisal =
          this.formApply.appraisal !== null ? parseInt(this.formApply.appraisal) : 0
        this.openErrorAlert =
          this.formApply.reason != null && this.formApply.reason !== ''
        this.auditRecord = res.data.auditRecord
        // 先清空上传列表，再显示已上传图片
        this.$refs.driverUploadFile.handleClearFiles()
        this.$refs.driverUploadFile.setData(res.data.apply_file.driver)
        if (this.displayHouqinForm) {
          this.$refs.houqinUploadFile.handleClearFiles()
          this.$refs.houqinUploadFile.setData(res.data.apply_file.houqin)
        }
        if (this.displayWeixiuForm) {
          this.$refs.weixiuUploadFile.handleClearFiles()
          this.$refs.weixiuUploadFile.setData(res.data.apply_file.weixiu)
        }
        // 字段只读
        this.isHouQinReadonly = true
        this.isReadonly = true
        this.isDisabled = true
        this.modalApplyVisible = true
      })
    },
    reasonAudit() {
      this.reasonAuditLoading = true
      this.toAuditApply(this.reasonForm)
    },
    toAddWeixiu() {
      this.modal = true
    },
    toAuditApply(params) {
      auditApply(params).then(res => {
        if (res.data.result === true) {
          if (res.data.nodeType === 'pass' || res.data.nodeType === 'end') {
            this.$Message.success(res.message)
          } else {
            this.reasonAuditLoading = false
            this.reasonModal = false
            this.$Message.error(res.message)
          }
          this.modalApplyVisible = false
          this.getMrApplyList()
        }
      })
    }
  }
}
</script>
<style scoped>
/*去除竖行分割线margin*/
.ivu-table-row .ivu-divider-vertical {
  margin: 0;
}

/* 审核记录 */
#auditRecord {
  padding: 0 2%;
}

#auditRecord .title {
  font-family: "Font Awesome 5 Pro Solid", "Font Awesome 5 Pro Regular",
  "Font Awesome 5 Pro", serif;
  font-weight: 900;
  font-style: normal;
  font-size: 16px;
  margin-top: 15px;
}

#auditRecord .stepCard {
  border: 1px solid rgba(215, 232, 244, 1);
  background-color: #f7fbfe;
  height: 120px;
  width: 90%;
  padding: 0 1%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  position: relative;
  left: 35px;
}

#auditRecord .stepCard > div:first-child {
  font-family: "微软雅黑", serif;
  font-weight: 400;
  font-size: 14px;
  color: #666;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

#auditRecord .stepCard > div:first-child > span {
  margin-top: 10px;
  color: #999;
}

#auditRecord .stepCard > div:nth-child(2) {
  margin-top: 20px;
  color: #666;
}

#auditRecord .stepCard > div:nth-child(2) > div {
  height: 70px;
  width: 120px;
  display: flex;
  white-space: nowrap;
  justify-content: space-between;
  line-height: 100px;
}

#auditRecord .stepCard > div:nth-child(2) > div img {
  width: 100%;
  height: 100%;
}

#auditRecord .stepCard > div:last-child {
  position: absolute;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: 1px solid #9ed1f5;
  left: -30px;
  top: 52px;
}

#auditRecord .pointIndex {
  background-color: #9ed1f5;
}
</style>
